﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Annual_faculty_promotions.Core.Domain;
using Annual_faculty_promotions.Data;
using Annual_faculty_promotions.Service.Contracts;
using Annual_faculty_promotions.WebUI.Helpers.Filters;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Annual_faculty_promotions.WebUI.Areas.UserArea.Controllers
{
    public class UnivercityStructureController : Controller
    {
        private readonly IUnivercityStructureService _univercityStructureService;
        private readonly IUnitOfWork _unitOfWork;

        public UnivercityStructureController(IUnitOfWork unitOfWork, IUnivercityStructureService univercityStructureService)
        {
            _unitOfWork = unitOfWork;
            _univercityStructureService = univercityStructureService;

        }
        public ActionResult Index()
        {
            return View();
        }


        public ActionResult GetStructuresTreeNode()
        {
            List<JObject> jobjects = new List<JObject>();

            var items = _univercityStructureService.GetAllUnivercityStructures();

            if (items.Any())
            {
                var rootNodes = items.Where(c => c.Level == 1);
                foreach (var node in rootNodes)
                {
                    JObject root = new JObject
                      {
                        {"id",node.Id},
                        {"text",node.Name},
                        {"hasChild",node.HasChild},
                        {"level",node.Level}
                      };
                    root.Add("children", this.GetChild(node, items));
                    jobjects.Add(root);
                }
            }
            return Content(JsonConvert.SerializeObject(jobjects));
        }
        private JArray GetChild(UnivercityStructure parentNodes, IEnumerable<UnivercityStructure> nodes)
        {
            JArray childArray = new JArray();

            foreach (var node in nodes.Where(x => x.ParentId == parentNodes.Id))
            {
                JObject subObject = new JObject
                {
                    {"id",node.Id},
                    {"text",node.Name},
                    {"hasChild",node.HasChild},
                    {"level",node.Level}
                };

                if (nodes.Any(y => y.ParentId == node.Id))
                {
                    subObject.Add("children", this.GetChild(node, nodes));
                }
                childArray.Add(subObject);
            }
            return childArray;
        }

        [HttpPost]
        [AjaxOnly]
        [OutputCache(NoStore = true, Duration = 0)]
        public ActionResult Create(UnivercityStructure univercityStructure)
        {
            if (ModelState.IsValid)
            {
                _univercityStructureService.AddNewUnivercityStructure(univercityStructure);
                _unitOfWork.SaveChanges();
                return Json(new
                {
                    Msg = "ثبت شد"
                });
            }
            else
            {
                return Json(new { Msg = "خطا - ثبت نشد" });
            }
        }


        public ActionResult GetCategoriesTreeNode()
        {
            List<JObject> jobjects = new List<JObject>();

            var items = _univercityStructureService.GetAllUnivercityStructures();

            if (items.Any())
            {
                var rootNodes = items.Where(c => c.Level == 1);
                foreach (var node in rootNodes)
                {
                    JObject root = new JObject
                      {
                        {"id",node.Id},
                        {"text",node.Name},
                        {"level",node.Level}
                      };
                    root.Add("children", this.GetChild(node, items));
                    jobjects.Add(root);
                }
            }
            return Content(JsonConvert.SerializeObject(jobjects));
        }


        private JArray GetChild(UnivercityStructure parentNodes, IList<UnivercityStructure> nodes)
        {
            JArray childArray = new JArray();

            foreach (var node in nodes.Where(x => x.ParentId == parentNodes.Id))
            {
                JObject subObject = new JObject
                {
                    {"id",node.Id},
                    {"text",node.Name},
                    {"level",node.Level}
                };

                if (nodes.Any(y => y.ParentId == node.Id))
                {
                    subObject.Add("children", this.GetChild(node, nodes));
                }
                childArray.Add(subObject);
            }
            return childArray;
        }

        //public ActionResult Getcolleges(int page = 1, int pageSize = 10)
        //{

        //    var sizes = _collegeService.GetAllCollegesAsQueryable()
        //        .OrderBy(x => x.Id)
        //        .Skip((page - 1) * pageSize)
        //        .Take(pageSize);

        //    JArray ja = new JArray();

        //    foreach (var item in sizes)
        //    {
        //        var itemObject = new JObject
        //        {
        //            {"Id",item.Id},
        //            {"Name",item.Name}
        //        };
        //        ja.Add(itemObject);
        //    }

        //    JObject jo = new JObject();
        //    jo.Add("total", _collegeService.GetAllCollegesAsQueryable().Count());
        //    jo.Add("rows", ja);
        //    return Content(JsonConvert.SerializeObject(jo), "application/json");
        //}


        //public ActionResult GetlistCollege()
        //{
        //    var colleges = _collegeService.GetAllCollegesAsQueryable();

        //    JArray ja = new JArray();

        //    foreach (var item in colleges)
        //    {
        //        var itemObject = new JObject
        //        {
        //            {"id",item.Id},
        //            {"text",item.Name}
        //        };
        //        ja.Add(itemObject);
        //    }
        //    return Content(JsonConvert.SerializeObject(ja), "application/json");
        //}

        //[HttpPost]
        //[AjaxOnly]
        //public ActionResult Create([Bind(Include = "Name")] College college)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        _collegeService.AddNewCollege(college);
        //        _unitOfWork.SaveChanges();
        //        return Json(new { Msg = "ثبت شد" });
        //    }
        //    return Json(new { Msg = "خطا در ثبت!" });
        //}


        [HttpPost]
        [AjaxOnly]
        public ActionResult Delete(int id)
        {
            try
            {
                var model = _univercityStructureService.Find(id);
                if (model == null)
                    return HttpNotFound();
                _univercityStructureService.Delete(id);
                _unitOfWork.SaveChanges();
                return Json(new { success = true, Msg = "حذف شد" });
            }
            catch (Exception)
            {

                return Json(new { success = false, Msg = "حذف نشد" });
            }
        }


        public ActionResult Edit(int? univercityId)
        {
            if (univercityId == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var college = _univercityStructureService.Find(univercityId);
            if (college == null)
            {
                return HttpNotFound();
            }
            return PartialView("_edit", college);
        }

        [HttpPost]
        public ActionResult Edit(UnivercityStructure univercity)
        {
            if (ModelState.IsValid)
            {
                _univercityStructureService.EditUnivercityStructure(univercity);
                _unitOfWork.SaveChanges();
                return Json(new { success = true, Msg = "تغییرات اعمال شد" });
            }
            return Json(new { success = false, Msg = "ورودی نامعتبر" });
        }   
    }
}